import os, json, logging

logger = logging.getLogger('NextApp-ONT-QC')


def __volume(cell_info_list):
    stat = {'cells': list(), 'meta': {'count': 0, 'total_bases': 0, 'total_reads': 0}}
    for cell_info in cell_info_list:
        cell_stat = {
            'cell': cell_info['cell'],
            'all_read_num': cell_info['stat']['qc']['all']['read_num'],
            'all_base_num': cell_info['stat']['qc']['all']['base_num'],
            'all_mean_len': cell_info['stat']['qc']['all']['mean_len'],
            'hq_base_num': cell_info['stat']['qc']['hq']['base_num'],
            'hq_read_num': cell_info['stat']['qc']['hq']['read_num'],
            'hq_mean_len': cell_info['stat']['qc']['hq']['mean_len'],
            'hq_medium_len': cell_info['stat']['qc']['hq']['medium_len'],
            'hq_max_len': cell_info['stat']['qc']['hq']['max_len'],
            'hq_min_len': cell_info['stat']['qc']['hq']['min_len'],
            'hq_mean_qscore': cell_info['stat']['qc']['hq']['mean_qscore'],
            'hq_n50_len': cell_info['stat']['hq_stat']['nx0']['read']['n50'][0]
        }
        stat['cells'].append(cell_stat)
        stat['meta']['count'] += 1
        stat['meta']['total_bases'] += cell_stat['hq_base_num']
        stat['meta']['total_reads'] += cell_stat['hq_read_num']
    stat['meta']['mean_bases'] = stat['meta']['total_bases'] / stat['meta']['count'] if stat['meta']['count'] != 0 else 0
    stat['meta']['mean_len'] = stat['meta']['total_bases'] / stat['meta']['total_reads'] if stat['meta']['total_reads'] != 0 else 0
    return stat


def __distribution(cell_info_list):
    stat = list()
    for cell_info in cell_info_list:
        cell_stat = {
            'cell': cell_info['cell'],
            'cumulative': cell_info['stat']['hq_stat']['distribution']['cumulative'],
            'interval': cell_info['stat']['hq_stat']['distribution']['interval']

        }
        stat.append(cell_stat)
    return stat


def run_stat(cell_info_list):
    volume_stat = __volume(cell_info_list)
    distribution_stat = __distribution(cell_info_list)
    return volume_stat, distribution_stat
